/**
 * Copyright 2010 Butin Kirill <kiryaka@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flexupload.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class FileUtils {
	public static void copyFile(File in, File out) throws IOException {
		FileChannel inChannel = new FileInputStream(in).getChannel();
		FileChannel outChannel = new FileOutputStream(out).getChannel();
		try {
			// magic number for Windows, 64Mb - 32Kb)
			int maxCount = (64 * 1024 * 1024) - (32 * 1024);
			long size = inChannel.size();
			long position = 0;
			while (position < size) {
				position += inChannel.transferTo(position, maxCount, outChannel);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}

	public static void writeToFileFromOffset(String filePath, int fileOffset, byte[] byteArray) throws IOException {
		RandomAccessFile out = null;
		try{
			out = new RandomAccessFile(filePath, "rw");
			out.seek(fileOffset);
			out.write(byteArray);
			out.close();
		}catch (IOException e) {
			throw e;
		}finally{
			if (out != null) out.close();
		}
	}

	public static void moveFile(String pathToFile, String newDestinationDirectory, String newDestinationFileName) throws IOException {
		File file = new File(pathToFile);
		File dir = new File(newDestinationDirectory);
		if (!dir.exists() && !dir.mkdirs())
			throw new IOException("Can't create destination directory: " + dir.getAbsolutePath());
		
		File newLocation = new File(newDestinationDirectory + "/" + newDestinationFileName);
		if (!file.renameTo( newLocation )) 
				copyFile(file, newLocation);
		file.delete();
	}
	
	public static byte[] readBytesFromFileWithOfset(String filename, int offset, int length) throws IOException {
		byte[] byte_array = new byte[length];
		FileInputStream fileStream = new FileInputStream(filename);	
		fileStream.skip(offset);
		fileStream.read(byte_array);
		fileStream.close();
		return byte_array;
	}

	public static void createFileWithGivenLength(File file, int length) throws IOException {
		RandomAccessFile rf = new RandomAccessFile(file, "rw");
		rf.setLength(length);
		rf.close();
	}	
}
